/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.etop.ondoc.dao;

import com.etop.ondoc.beans.Category;
import com.etop.ondoc.util.HibernateUtil;
import org.hibernate.Session;

/**
 *
 * @author jansing
 * lz_jansing@163.com
 */
public class CategoryDao {
    
    public Category load(int id){
        Session session = HibernateUtil.openSession();
        Category cate = (Category) session.get(Category.class, id);
        session.close();
        return cate;
    }
    public Category loadByName(String name){
        Session session = HibernateUtil.openSession();
        Category cate = (Category) session.createQuery("from Category where name=:name")
                .setString("name", name)
                .uniqueResult();
        HibernateUtil.close(session);
        return cate;
    }
    public void add(Category cate){
        Session session = null;
        try{
            session = HibernateUtil.openSession();
            session.beginTransaction();
            session.save(cate);
            session.getTransaction().commit();
        } catch(Exception e){
            System.out.println("添加分类失败！");
            if(session!=null){
                session.getTransaction().rollback();
            }
        }finally{
            HibernateUtil.close(session);
        }
    }
    public void update(Category cate){
        Session session = null;
        try{
            session = HibernateUtil.openSession();
            session.beginTransaction();
            session.update(cate);
            session.getTransaction().commit();
        } catch(Exception e){
            System.out.println("更新分类失败！");
            if(session!=null){
                session.getTransaction().rollback();
            }
        }finally{
            HibernateUtil.close(session);
        }
    }
    public void delete(Category cate){
        Session session = null;
        try{
            session = HibernateUtil.openSession();
            session.beginTransaction();
            cate.setIsVaild(Category.IS_NOT_VAILD);
            session.update(cate);
            session.getTransaction().commit();
        } catch(Exception e){
            System.out.println("删除分类失败！");
            if(session!=null){
                session.getTransaction().rollback();
            }
        }finally{
            HibernateUtil.close(session);
        }
    }

}
